package com.dc.management.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dc.management.pojo.News;
import com.dc.management.pojo.TbUser;
import com.dc.management.services.NewsService;
import com.dc.management.services.UserService;
import com.dc.management.util.Util;

public class PublishNewsServlet extends HttpServlet {
	
	private NewsService service ;

	/**
	 * Constructor of the object.
	 */
	public PublishNewsServlet() {
		super();
		service = new NewsService();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("PublishNewsServlet .....");

		String command = request.getParameter("command");
		String news_title = request.getParameter("title");
		String new_content= request.getParameter("content");
		String publisher_id= request.getParameter("publisher_id");
		
		if("publish".equals(command)){
			
			News news = new News();
			news.setTitle(news_title);
			news.setContent(new_content);
			news.setPublisher_id(publisher_id);
			news.setPublish_time(Util.getStrTime(Calendar.getInstance().getTime(), "yyyyMMddHHmmss"));
			
			
			service.publish(news);
			
			uploadFileToServer(request, response);
			
			response.sendRedirect("success.jsp");
			
		}else if("query_by_page".equals(command)){
			
			String pageSize = request.getParameter("pageSize");
			String pageNum = request.getParameter("pageNum");
			String publish_time = request.getParameter("publish_time");
			
			
			List<News> newses = service.listNewsByPage(pageNum,pageSize,publish_time);
			JSONArray json  = JSONArray.fromObject(newses);
			
			ServletOutputStream out= response.getOutputStream();
			out.println( json.toString() );
			out.flush();
			out.close();
		}else if("list".equals(command)){
			List<News> newses = service.listNews();
			JSONArray json  = JSONArray.fromObject(newses);
			
			ServletOutputStream out= response.getOutputStream();
			out.println( json.toString() );
			out.flush();
			out.close();
		}
		
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	
	public void uploadFileToServer(HttpServletRequest request, HttpServletResponse response){
		System.out.println("uploadFileToServer......");
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(4096);
		// the location for saving data that is larger than getSizeThreshold()
		new File("/tmp").mkdir();
		factory.setRepository(new File("/tmp"));

		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(1000000);

		List fileItems = null;
		try {
			fileItems = upload.parseRequest(request);
			Iterator i = fileItems.iterator();
			while(i.hasNext()){
			
				FileItem fi = (FileItem) i.next();
				String fileName = fi.getName();
				System.out.println("fileName "+fileName+" ; contentTypte "+ fi.getContentType());
							
				// save comment and filename to database
				File file= new File("E:/upload");
				if(!file.exists()){
					file.mkdir();
				}
				
				String tempFileName = fileName.substring(fileName.lastIndexOf("\\")+1);
				File myFile = new File(file, tempFileName);
				
				System.out.println(myFile.getName());
				myFile.createNewFile();
				
				fi.write(myFile);
			}
			
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
